<?php

if (isset($_REQUEST['id'])) {
	$page = $db->fetchRow("SELECT * FROM site_pages WHERE id=? AND site_id=?", array($_REQUEST['id'], $site['id']));
} else {
	$page = $db->fetchRow("SELECT * FROM site_pages WHERE parent_id=? AND site_id=?", array(0, $site['id']));
}

$page['revision'] = $db->fetchRow("SELECT * FROM site_pages_revisions WHERE page_id=? ORDER BY id DESC LIMIT 1", $page['id']);
$page['content']  = $db->fetchPairs("SELECT name, value FROM site_pages_revisions_content WHERE revision_id=?", $page['revision']['id']);
$page['plugins'] = array_index($db->fetchAll("SELECT file, config, manage_path FROM site_pages_revisions_plugins WHERE revision_id=?", $page['revision']['id']), 'file');
$page['revision']['robots'] = unserialize($page['revision']['robots']);

/*
 * Find available plugins
 *
 */
$all_plugins = array();
foreach(glob($app_root . $site['home_dir'] . '/plugins/*') as $file) {
	if (is_dir($file) and file_exists($file .'/' . basename($file) . '.php')) {
		$file = $file .'/' . basename($file) . '.php';
	}
	if (preg_match('/\.php$/m', $file)) {
		$plugin = parse_plugin($file, $page['plugins']);
		if (isset($plugin['name'])) {
			$all_plugins[$plugin['file']] = $plugin;
		}
	}
}
foreach(glob($app_root . '/admin/plugins/*') as $file) {
	if (is_dir($file) and file_exists($file .'/' . basename($file) . '.php')) {
		$file = $file .'/' . basename($file) . '.php';
	}
	if (preg_match('/\.php$/', $file)) {
		$plugin = parse_plugin($file, $page['plugins']);
		if (isset($plugin['name'])) {
			$all_plugins[$plugin['file']] = $plugin;
		}
	}
}
uasort($all_plugins, create_function('$a,$b', 'return ($a["name"] < $b["name"]) ? -1 : 1;'));
$page['plugins'] = $all_plugins;

/*
 * If we've got posted data - then update
 *
 */
if (isset($_POST['page'])) {
	if (isset($_POST['page']['revision']['path']) and !$_POST['page']['revision']['path']) $_POST['page']['revision']['path'] = make_path($_POST['page']['revision']['title']);
	if (isset($_POST['page']['revision']['robots'])) $_POST['page']['revision']['robots'] = serialize($_POST['page']['revision']['robots']);
	
	$page['revision'] = array_merge($page['revision'], $_POST['page']['revision']);
	if (isset($_POST['page']['content'])) $page['content'] = array_merge($page['content'], $_POST['page']['content']);
	if (isset($_POST['page']['plugins'])) {
		foreach($_POST['page']['plugins'] as $file => $plugin) {
			unset($page['plugins'][$file]['manage_path']);
			$page['plugins'][$file] = array_merge($page['plugins'][$file], $_POST['page']['plugins'][$file]);
			if (!isset($_POST['page']['plugins'][$file]['enabled'])) unset($page['plugins'][$file]['enabled']);
		}
	}	
	if ($page['revision']['context'] == '_other_') $page['revision']['context'] = $_POST['context_other'];
	
	$errors = array();
	
	if (!$page['revision']['title']) $errors[] = 'TITLE';
	if ($page['revision']['context'] == '') $errors[] = 'CONTEXT';
	//if ($db->fetchOne("SELECT MAX(r.id) FROM site_pages p LEFT JOIN site_pages_revisions r ON p.id=r.page_id WHERE p.site_id=? AND parent_id=? AND path=? GROUP BY p.id", array($site['id'], $page['parent_id'], $page['revision']['path']))) $errors[] = 'PATH_UNIQUE';
	if (sizeof($errors)) {
		$smarty->assign('errors', $errors);
	} else {
		unset($page['revision']['id']);
		$smarty->assign('success', true);
		$db->insert('site_pages_revisions', array_merge($page['revision'], array('timestamp' => new Zend_Db_Expr('NOW()'), 'published' => new Zend_Db_Expr('NULL'))));
		$page['revision_id'] = $db->lastInsertId();
		foreach($page['content'] as $name => $value) {
			$db->insert('site_pages_revisions_content', array(
				'revision_id' => $page['revision_id'],
				'name' => $name, 
				'value' => $value
			));
		}
		foreach($page['plugins'] as $file => $plugin) {
			if (isset($plugin['enabled']) and $plugin['enabled']) {
				$db->insert('site_pages_revisions_plugins', array(
					'revision_id' => $page['revision_id'],
					'file'        => $file,
					'config'      => $plugin['config'],
					'manage_path' => isset($plugin['manage_path']) ? 1 : 0
				));
			}
		}
	}
	$page['revision']['robots'] = unserialize($page['revision']['robots']);
	
}

/*
 * Generate files & folders lists for use in template variables
 *
 */
$image_list = array();
image_list();
function image_list($parent_id=0, $parent_folders='') {
	global $db, $site, $image_list;
	$folders = $db->fetchAll("SELECT id, title FROM cms_images_folders WHERE site_id=? AND parent_id=? ORDER BY title", array($site['id'], $parent_id));
	foreach($folders as $folder) {
		$folder['title'] = strlen($parent_folders) ? $parent_folders . ' » ' . $folder['title'] : $folder['title'];
		$folder['type']  = 'folder';
		$image_list[] = $folder;
		$images = $db->fetchAll("SELECT id, filename FROM cms_images WHERE site_id=? AND folder_id=? ORDER BY sort", array($site['id'], $folder['id']));
		foreach($images as $image) {
			$image['title'] = $folder['title'] . ' » ' . $image['filename'];
			$image['type']  = 'image';
			$image_list[] = $image;
		}
		image_list($folder['id'], $folder['title']);
	}
}
$smarty->assign('image_list', $image_list);

$file_list = array();
file_list();
function file_list($parent_id=0, $parent_folders='') {
	global $db, $site, $file_list;
	$folders = $db->fetchAll("SELECT id, title FROM cms_files_folders WHERE site_id=? AND parent_id=?", array($site['id'], $parent_id));
	foreach($folders as $folder) {
		$folder['title'] = strlen($parent_folders) ? $parent_folders . ' » ' . $folder['title'] : $folder['title'];
		$folder['type']  = 'folder';
		$file_list[] = $folder;
		$files = $db->fetchAll("SELECT id, filename FROM cms_files WHERE site_id=? AND folder_id=?", array($site['id'], $folder['id']));
		foreach($files as $file) {
			$file['title'] = $folder['title'] . ' » ' . $file['filename'];
			$file['type']  = 'file';
			$file_list[] = $file;
		}
		file_list($folder['id'], $folder['title']);
	}
}
$smarty->assign('file_list', $file_list);

$link_list = array();
link_list();
function link_list($parent_id=null, $current_path='/') {
	global $link_list, $db, $site, $env;
	if ($parent_id == null) {
		// get the top most page
		list($parent_id, $title) = array_values($db->fetchRow("SELECT p.id, title FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id WHERE site_id=? AND parent_id=0", $site['id']));
		if (!$parent_id) {
			return;
		}
	}
	$pages = $db->fetchAll("SELECT p.id, r.title, r.path, r.link FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id WHERE p.site_id=? AND p.parent_id=? AND active=1 ORDER BY sort", array($site['id'], $parent_id));
	for($i=0;$i<count($pages);$i++) {
		$pages[$i]['full_path'] =  $current_path . $pages[$i]['path'] . '/';
		$link_list[] = $pages[$i]['full_path'];
		$pages[$i]['children'] = link_list($pages[$i]['id'], $pages[$i]['full_path']);
	}
}
$smarty->assign('link_list', $link_list);

/*
 * Get templates
 *
 */
$template_var_names = array_flatten(parse_template_vars('site/' . $db->fetchOne("SELECT file FROM site_templates WHERE id=?", $page['revision']['template_id'])));
$seen_vars = array();
foreach ($template_var_names as $var_name) {
	if (!in_array($var_name, $seen_vars)) {
		$var = array();
		@list($var['name'], $var['type'], $ignore, $var['config']) = preg_extract("/^(.+?)\|var:'(.*?)'(:'(.*?)')?$/", $var_name);
		
		$var['title'] = str_replace('_', ' ', $var['name']);
		
		if ($var['type'] == 'Select') {
			$var['options'] = split(':', $var['config']);
		}
		
		$smarty->append('template_vars', $var);
		$seen_vars[] = $var_name;
	}
}

/*
 * recursively traverse templates, extracting template variables. 
 *
 */
function parse_template_vars($filename, $seen = array()) {
	global $app_root, $site;
	$vars = array();
	
	if (in_array($filename, $seen)) return false;
	$seen[] = $filename;
	
	$template_source = @file_get_contents($app_root . $site['home_dir'] . '/templates/' . $filename);
	$template_vars = array_slice(preg_extract_all("/(\{include file=\"(.*?)\"\}|\\\$(([^\$]*?)\|var(:'.*?')?)[\.\}\| ])/", $template_source), 1);
	for($i=0;$i<count($template_vars[0]);$i++) {
		if ($template_vars[0][$i]) {
			$template_vars[1][$i] = parse_template_vars($template_vars[0][$i], $seen);
		}
	}
	for($i=0;$i<count($template_vars[1]);$i++) {
		// TODO: Check why this needs @ on some pages - shouldn't really need
		$template_var = @preg_split('/\|/', $template_vars[1][$i], 2);
		if (in_array($template_var[0], $seen)) {
			unset($template_vars[1][$i]);
		} else {
			$seen[] = $template_var[0];
		}
	}
	return array_filter($template_vars[1]);
}

/*
 * Get breadcrumb
 *
 */
$breadcrumb = array();
$current_page = $page;
while($current_page['parent_id']) {
	$current_page = $db->fetchRow("SELECT id, parent_id, (SELECT title FROM site_pages_revisions WHERE page_id=p.id ORDER BY id DESC LIMIT 1) AS title, (SELECT path FROM site_pages_revisions WHERE page_id=p.id ORDER BY id DESC LIMIT 1) AS path FROM site_pages p WHERE id=?", $current_page['parent_id']);
	$breadcrumb[] = $current_page;
}
$smarty->assign('breadcrumb', array_reverse($breadcrumb));

$smarty->assign('page', $page);
$smarty->assign('templates', $db->fetchAll("SELECT * FROM site_templates WHERE site_id=? ORDER BY sort", $site['id']));
$smarty->assign('contexts', $db->fetchCol('SELECT DISTINCT r.context FROM site_pages p JOIN site_pages_revisions r ON r.id=(SELECT MAX(id) FROM site_pages_revisions WHERE page_id=p.id) WHERE site_id=?', $site['id']));

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
	header('Content-type: text/xml');
	if (isset($template_changed)) $smarty->assign('template_changed', $template_changed);
	$smarty->display('site/pages/index.tpl.taconite');
} else {
	$smarty->display('site/pages/index.tpl.html');
}
